<script lang="ts">
import { Message, Money, Tickets, Star, User, SwitchButton, CaretBottom, UserFilled, Notebook } from '@element-plus/icons-vue'

import { ComponentSize, ElMessage, ElMessageBox } from 'element-plus';

import { onMounted, ref } from 'vue'
import { useTokenStore } from '@/stores/token'

//导入接口函数
import { userInfoGetService } from '@/api/user.js'
//导入pinia
import { useUserInfoStore } from '@/stores/userInfo.js'
import { communityService } from '@/api/community';
import router from '@/router';
const userInfoStore = useUserInfoStore();

//获取个人信息
const getUserInfo = async () => {
    let result = await userInfoGetService();
    //存储pinia
    userInfoStore.info = result.data;
}
getUserInfo()


const currentPage4 = ref(1)
const pageSize4 = ref(5)
const size = ref<ComponentSize>('default')

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
}

const handleOpen = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}

const getCommunity = async () => {}
getCommunity();
const posts = ref([
    {
        "id": '',
        "content": "",
        "postType": "",
        "likeCount": 0,
        "viewCount": 0,
        "videoUrl": "",
        "coverImg": null,
        "createTime": "",
        "updateTime": "",
        "title": ""
    }
])

const updateLocalStorage = () => {
    const likedPosts = posts.value.reduce((acc, post) => {
        acc[post.id] = { likeCount: post.likeCount, viewCount: post.viewCount };
        return acc;
    }, {});
    localStorage.setItem('likedPosts', JSON.stringify(likedPosts));
};

const loadLikedPosts = () => {
    const likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};
    posts.value.forEach(post => {
        if (likedPosts[post.id]) {
            post.likeCount = likedPosts[post.id].likeCount;
            post.viewCount = likedPosts[post.id].viewCount;
        }
    });
};

onMounted(() => {
    getCommunity();
    loadLikedPosts();
});


const handleCommand = (command) => {
    if (command === 'logout') {
        //退出登录
        ElMessageBox.confirm(
            '你确认退出登录吗？',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                try {
                    // 清空pinia中的token和个人信息
                    const tokenStore = useTokenStore();
                    tokenStore.removeToken();

                    // 跳转到登录页
                    router.push('/login');

                    // 更新 localStorage
                    localStorage.setItem('isLoggedIn', 'false');
                } catch (error) {
                    console.error("发生错误：", error);
                    // 可以选择是否在这里显示错误消息或其他处理
                }
            })
            .catch(() => {
                // 用户点击了取消
                ElMessage({
                    type: 'info',
                    message: '取消退出',
                });
            });
    }
}
export default {
    components: {
        Message,
        Money,
        Tickets,
        Star,
        User,
        SwitchButton,
        CaretBottom,
        UserFilled,
        Notebook,
    },
    data() {
        return {
            handleOpen: '',
            handleClose: '',
            activeIndex: '2',
            searchQuery: '',
            isDark: false,
            currentPage4,
            pageSize4,
            size,
            posts,
            handleSizeChange,
            handleCurrentChange,
            handleLike: '',
            handlefavorite: '',
            User,
            SwitchButton,
            UserFilled,
            Notebook,
            userInfoStore,
            userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            handleSelect: '',
            recharge: '',
            withdraw: '',
            handleCommand,
        }
    },
    methods: {
        setDefaultLogo(event) {
            event.target.src = 'images/default-logo.jpg';
        },
        search() {
            // 处理搜索逻辑
            console.log(`搜索内容: ${this.searchQuery}`);
        },
        filter(option) {
            // 处理过滤逻辑
            console.log(`过滤选项: ${option}`);
        },
        navigateTologin(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        navigateToregister(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        navigateTo(link) {
            window.location.href = link;
        },
        handleLike(postId) {
            const post = this.posts.find(post => post.id === postId);
            if (post) {
                post.likeCount += 1;
                console.log(`帖子 ${postId} 被点赞了! 当前点赞数: ${post.likeCount}`);
                updateLocalStorage();
            } else {
                console.log(`没有找到 ID 为 ${postId} 的帖子`);
            }
        },
        handlefavorite(postId) {
            const post = this.posts.find(post => post.id === postId);
            if (post) {
                post.viewCount += 1;
                console.log(`帖子 ${postId} 被收藏了! 当前收藏数: ${post.viewCount}`);
                updateLocalStorage();
            } else {
                console.log(`没有找到 ID 为 ${postId} 的帖子`);
            }
        },
    }
}
</script>

<template>
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        @select="handleSelect" style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <el-menu-item index="0">
            <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg"
                alt="CodeCash" />
        </el-menu-item>
        <el-search-item index="1" style="transform: translate(-100%,15px);">
            <el-input v-model="searchQuery" style="width: 300px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
            <el-button type="search" style="height: 40px;background-color:#007bff;color:white;">搜索</el-button>
        </el-search-item>
        <el-router-menu index="2" style="transform: translateX(-2%);">
            <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
            <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
            <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
            <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
            <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
        </el-router-menu>
        <el-buttons-item index="3" style="transform: translateY(25%);margin-right: 20px;">
            <el-dropdown placement="bottom-end">
                <el-avatar :src="userAvatar" size="medium" />
                <el-icon>
                    <CaretBottom />
                </el-icon>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="userInfo" :icon="User"
                            @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
                        <el-dropdown-item command="logout" :icon="SwitchButton"
                            @click="handleCommand('logout')">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-buttons-item>
    </el-menu>
    <el-aside width="200px" height="700vh" style="margin-left: 300px;">
        <div
            style="margin-left: -40px;margin-top: 20px;align-items: center;justify-content: center;display: flex;flex-direction: column;">
            <el-avatar src="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif" />
            <h5 class="mb-2">{{ userInfoStore.info.username }}</h5>
            <el-button color="#2994F2">已签约</el-button>
        </div>
        <el-divider />
        <el-menu default-active="4" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
            <el-menu-item index="1" @click="navigateTo('/userInfo')">
                <el-icon>
                    <Money />
                </el-icon>
                <span>账户金额</span>
            </el-menu-item>
            <el-menu-item index="2" @click="navigateTo('/userInfo/message')">
                <el-icon>
                    <Message />
                </el-icon>
                <span>账户信息</span>
            </el-menu-item>
            <el-menu-item index="3" @click="navigateTo('/userInfo/task')">
                <el-icon>
                    <Notebook />
                </el-icon>
                <span>我的任务</span>
            </el-menu-item>
            <el-menu-item index="4" @click="navigateTo('/userInfo/favorite')">
                <el-icon>
                    <Star />
                </el-icon>
                <span>我的收藏</span>
            </el-menu-item>
            <el-menu-item index="5" @click="navigateTo('/userInfo/list')">
                <el-icon>
                    <Tickets />
                </el-icon>
                <span>订单列表</span>
            </el-menu-item>
        </el-menu>
    </el-aside>
    <el-container style="margin-left: 100px;margin-top: 30px;">
        <el-header style="margin-left: 240px;margin-top: -400px;">
            <div class="box-card" v-for="post in posts" :key="post.id">
                <div style="padding: 10px;">
                    <el-avatar :src="userAvatar" :size="60" />
                </div>
                <div class="card-body">
                    <p style="color: #2994F2;">帖子类型：{{ post.postType }}</p>
                    <h3 style="margin-bottom: 5px;">{{ post.title }}</h3>
                    <p style="margin-top: 0;">{{ post.content }}</p>
                    <p style="margin-top: 0;">发布时间：{{ post.createTime }}</p>
                </div>
                <div class="card-foot">
                    <div style="display: flex;align-items: center;padding: 5px;">
                        <img src="@/assets/like.png" alt="点赞" style="width: 20px; height: 20px;">
                        <span style="margin-left: 10px;" @click="handleLike(post.id)" prop="likeCount">{{ post.likeCount
                            }}</span>
                    </div>
                    <div style="display: flex;align-items: center;padding: 5px;">
                        <img src="@/assets/favorite.png" alt="收藏" style="width: 20px; height: 20px;">
                        <span style="margin-left: 10px;" @click="handlefavorite(post.id)" prop="viewCount">{{
                            post.viewCount
                        }}</span>
                    </div>
                    <div style="display: flex;align-items: center;padding: 5px;">
                        <img src="@/assets/comment.png" alt="评论" style="width: 20px; height: 20px;">
                        <span style="margin-left: 10px;">评论</span>
                    </div>
                </div>
            </div>
            <el-pagination style="margin-left: 340px;margin-top: 140px;" v-model:current-page="currentPage4"
                v-model:page-size="pageSize4" :page-sizes="[5, 10, 15, 20]" :size="size"
                layout="total, sizes, prev, pager, next, jumper" :total="30" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-header>
    </el-container>
    <el-footer>
        <div class="footer">
            <div>
                <a href="#">动态公告</a> |
                <a href="#">帮助</a> |
                <a href="#">关于我们</a> |
                <a href="#">合作伙伴</a> |
                <a href="#">意见反馈</a> |
                <text style="color: rgb(78, 77, 77);">@“码上有钱”程序员接单平台</text>
            </div>
            <div class="credits">
                粤ICP备20220901号-4 | 粤公网安备33011002011599号
            </div>
        </div>
    </el-footer>
</template>

<style>
.el-menu--horizontal>.el-menu-item:nth-child(1) {
    margin-right: auto;
}

.box-card {
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border: 1px solid white;
    align-items: center;
    justify-content: center;
    width: 65%;
    height: auto;
    margin-right: 400px;
    flex-direction: column;
    margin: auto;
}


.card-body {
    margin-left: 100px;
    margin-top: -90px;
}

.card-body p {
    word-wrap: break-word;
    /* 在需要时换行 */
    overflow-wrap: break-word;
    /* 现代浏览器支持 */
}

.card-foot {
    margin-top: -40px;
    margin-left: 600px;
    display: flex;
    position: absolute;
}

.footer {
    margin-top: 300px;
    padding: 10px 0;
    border-top: 1px solid #ddd;
    text-align: center;
}

.footer a {
    text-decoration: none;
    color: rgb(78, 77, 77);
    background: transparent;
    border: none;
    cursor: pointer;
}

.footer .credits {
    margin-top: 5px;
    font-size: 12px;
    color: gray;
}
</style>